package me.wcy.music.activity;

/**
 * 获取 音乐列表
 */

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import me.wcy.music.R;
import me.wcy.music.adapter.OnMoreClickListener;
import me.wcy.music.adapter.OnlineMusicAdapter;
import me.wcy.music.application.AppCache;
import me.wcy.music.executor.DownloadOnlineMusic;
import me.wcy.music.executor.PlayOnlineMusic;
import me.wcy.music.http.HttpCallback;
import me.wcy.music.http.HttpClient;
import me.wcy.music.model.Music;
import me.wcy.music.model.OnlineMusic;
import me.wcy.music.model.OnlineMusicList;
import me.wcy.music.service.OnPlayerEventListener;
import me.wcy.music.service.PlayService;
import me.wcy.music.service.PlayerEventListenerImpl;
import me.wcy.music.utils.CoverLoader;
import me.wcy.music.utils.FileUtils;
import me.wcy.music.utils.ToastUtils;
import me.wcy.music.utils.binding.Bind;
import me.wcy.music.widget.AutoLoadListView;

public class PlaylistActivity extends BaseActivity implements OnItemClickListener, OnMoreClickListener, View.OnClickListener {
    @Bind(R.id.lv_online_music_list)
    private AutoLoadListView lvOnlineMusic;
    private List<OnlineMusic> mMusicList = new ArrayList<>();
    private OnlineMusicAdapter mAdapter = new OnlineMusicAdapter(mMusicList);
    //播放按钮控件组
    @Bind(R.id.iv_play_bar_play)
    private ImageView ivPlayBarPlay;
    @Bind(R.id.iv_play_bar_next)
    private ImageView ivPlayBarNext;
    @Bind(R.id.pb_play_bar)
    private ProgressBar mProgressBar;//进度条
    @Bind(R.id.iv_play_bar_cover)
    private ImageView ivPlayBarCover;//封面
    @Bind(R.id.tv_play_bar_title)
    private TextView tvPlayBarTitle;//标题
    @Bind(R.id.tv_play_bar_artist)
    private TextView tvPlayBarArtist;//专辑等
    PlayerEventListenerImpl mPlayerEvent=new PlayerEventListenerImpl() {
        // <editor-fold defaultstate="collapsed" desc="更新进度">
        @Override
        public void onPublish(int progress) {
            mProgressBar.setProgress(progress);
        }
        // </editor-fold>
        // <editor-fold defaultstate="collapsed" desc="切换音监听">
        @Override
        public void onChange(Music music) {
            onPlay(music);
        }
        // </editor-fold>
        // <editor-fold defaultstate="collapsed" desc="暂停">
        @Override
        public void onPlayerPause() {
            ivPlayBarPlay.setSelected(false);
        }
        // </editor-fold>
        // <editor-fold defaultstate="collapsed" desc="当前是播放状态">
        @Override
        public void onPlayerResume() {
            ivPlayBarPlay.setSelected(true);
        }
        // </editor-fold>
    };
    public void onPlay(Music music) {//
        if (music == null) {
            return;
        }

        Bitmap cover = CoverLoader.getInstance().loadThumbnail(music);
        ivPlayBarCover.setImageBitmap(cover);
        tvPlayBarTitle.setText(music.getTitle());
        tvPlayBarArtist.setText(music.getArtist());
        if (getPlayService().isPlaying() || getPlayService().isPreparing()) {
            ivPlayBarPlay.setSelected(true);
        } else {
            ivPlayBarPlay.setSelected(false);
        }
        mProgressBar.setMax((int) music.getDuration());
        mProgressBar.setProgress(0);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playlist);
        if (!checkServiceAlive()) {
            return;
        }
        init();
        getMusic(0);
        getPlayService().setOnPlayEventListener(mPlayerEvent);
    }

    private void init() {
        lvOnlineMusic.setAdapter(mAdapter);
    }

    @Override
    protected void setListener() {
        lvOnlineMusic.setOnItemClickListener(this);
        mAdapter.setOnMoreClickListener(this);

        ivPlayBarPlay.setOnClickListener(this);
        ivPlayBarNext.setOnClickListener(this);
    }

    private void getMusic(final int offset) {
        HttpClient.getSongListInfo("2", 20, offset, new HttpCallback<OnlineMusicList>() {
            @Override
            public void onSuccess(OnlineMusicList response) {
                List<OnlineMusic> a = response.getSong_list();

                lvOnlineMusic.onLoadComplete();
                if (offset == 0 && response == null) {
//                    ViewUtils.changeViewState(lvOnlineMusic, llLoading, llLoadFail, LoadStateEnum.LOAD_FAIL);
                    return;
                } else if (offset == 0) {
//                    initHeader();
//                    ViewUtils.changeViewState(lvOnlineMusic, llLoading, llLoadFail, LoadStateEnum.LOAD_SUCCESS);
                }
                if (response == null || response.getSong_list() == null || response.getSong_list().size() == 0) {
                    lvOnlineMusic.setEnable(false);
                    return;
                }
                mMusicList.addAll(response.getSong_list());
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFail(Exception e) {
                lvOnlineMusic.onLoadComplete();
                if (e instanceof RuntimeException) {
                    // 歌曲全部加载完成
                    lvOnlineMusic.setEnable(false);
                    return;
                }
                if (offset == 0) {
//                    ViewUtils.changeViewState(lvOnlineMusic, llLoading, llLoadFail, LoadStateEnum.LOAD_FAIL);
                } else {
                    ToastUtils.show(R.string.load_fail);
                }
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        play((OnlineMusic) parent.getAdapter().getItem(position));
    }

    // adapter 点击更多传过来的//判断本地是否存在  存在的话,不显示下载按钮
    @Override
    public void onMoreClick(int position) {
        final OnlineMusic onlineMusic = mMusicList.get(position);
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(mMusicList.get(position).getTitle());
        String path = FileUtils.getMusicDir() + FileUtils.getMp3FileName(onlineMusic.getArtist_name(), onlineMusic.getTitle());
        File file = new File(path);
        int itemsId = file.exists() ? R.array.online_music_dialog_without_download : R.array.online_music_dialog;
        dialog.setItems(itemsId, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 2:// 下载
                        download(onlineMusic);
                        break;
                }
            }
        });
        dialog.show();
    }

    // <editor-fold defaultstate="collapsed" desc="下载音乐链接,回调播放">
    private void play(OnlineMusic onlineMusic) {
        new PlayOnlineMusic(this, onlineMusic) {
            @Override
            public void onPrepare() {
//                mProgressDialog.show();
            }

            @Override
            public void onExecuteSuccess(Music music) {
//                mProgressDialog.cancel();
                getPlayService().play(music);
                ToastUtils.show(getString(R.string.now_play, music.getTitle()));
                Log.e("获取的Url", music.toString());

            }

            @Override
            public void onExecuteFail(Exception e) {
                ToastUtils.show(R.string.unable_to_play);
            }
        }.execute();
    }
    // </editor-fold>

    //下载
    private void download(final OnlineMusic onlineMusic) {
        new DownloadOnlineMusic(this, onlineMusic) {
            @Override
            public void onPrepare() {
//                mProgressDialog.show();
            }

            @Override
            public void onExecuteSuccess(Void aVoid) {
//                mProgressDialog.cancel();
                ToastUtils.show(getString(R.string.now_download, onlineMusic.getTitle()));
            }

            @Override
            public void onExecuteFail(Exception e) {
                ToastUtils.show(R.string.unable_to_download);
            }
        }.execute();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_play_bar_play:
                play();
                break;
            case R.id.iv_play_bar_next:
                next();
                break;
            default:
                break;
        }
    }
    private void play() {
        getPlayService().playPause();
    }
    private void next() {
        getPlayService().next();
    }
    // <editor-fold defaultstate="collapsed" desc="主要是销毁监听防止控件空指针">
    @Override
    protected void onDestroy() {
        PlayService service = AppCache.getPlayService();
        if (service != null) {
            service.setOnPlayEventListener(null);
        }
        super.onDestroy();
    }
    // </editor-fold>

}
